package com.example.dw.admin.service.impl;

import com.example.dw.admin.dto.PageRequestDTO;
import com.example.dw.admin.dto.CreateActivityDTO;
import com.example.dw.admin.dto.UpdateActivityDTO;
import com.example.dw.admin.service.AdminActivityService;
import com.example.dw.entity.Activity;
import com.example.dw.entity.ActivityBigType;
import com.example.dw.entity.ActivitySession;
import com.example.dw.entity.SessionPrice;
import com.example.dw.mapper.ActivityMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dw.mapper.ActivitySessionMapper;
import com.example.dw.mapper.ActivityBigTypeMapper;
import com.example.dw.mapper.SessionPriceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端活动管理服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class AdminActivityServiceImpl implements AdminActivityService {

    @Autowired
    private ActivitySessionMapper activitySessionMapper;

    // 价格mapper
    @Autowired
    private SessionPriceMapper sessionPriceMapper;

    @Autowired
    private ActivityMapper activityMapper;

    //活动大类
    @Autowired
    private ActivityBigTypeMapper activityBigTypeMapper;

    @Override
    public List<Activity> getSomeActivity(Integer count) {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activityState", 1);
        queryWrapper.orderByDesc("createdAt");
        queryWrapper.last("LIMIT " + count);
        
        return activityMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> getActivityByPage(PageRequestDTO pageRequest) {
        Page<Activity> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(pageRequest.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like("activityName", pageRequest.getKeyword())
                .or().like("activityDescribe", pageRequest.getKeyword())
                .or().like("activityPlace", pageRequest.getKeyword())
                .or().like("activityContent", pageRequest.getKeyword())
            );
        }
        
        // 状态筛选
        if (pageRequest.getStatus() != null) {
            queryWrapper.eq("activityState", pageRequest.getStatus());
        }
        
        queryWrapper.orderByDesc("createdAt");
        IPage<Activity> result = activityMapper.selectPage(page, queryWrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("list", result.getRecords());
        response.put("total", result.getTotal());
        response.put("page", result.getCurrent());
        response.put("size", result.getSize());
        
        return response;
    }

    @Override
    public Activity getActivityById(Integer activityid) {
        Activity activity = activityMapper.getActivityById(activityid);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
         // 获取活动类型
        ActivityBigType activityBigType = activityBigTypeMapper.getActivityBigTypeById(activity.getBigid());
        activity.setBigType(activityBigType);

        //  根据互动id获取所有场次，再遍历所有场次id获取价格
        List<ActivitySession> activitySessions = activitySessionMapper.getActivitySessionByActivityId(activityid);
        log.info("活动ID: {}, 查询到的场次数量: {}", activityid, activitySessions != null ? activitySessions.size() : 0);

        // 如果activitySessions为null，初始化为空列表
        if (activitySessions == null) {
            activitySessions = new java.util.ArrayList<>();
        } else {
            for (ActivitySession activitySession : activitySessions) {
                List<SessionPrice> sessionPrices = sessionPriceMapper.getSessionPriceBySessionId(activitySession.getSessionid());
                log.info("场次ID: {}, 查询到的价格数量: {}", activitySession.getSessionid(), sessionPrices != null ? sessionPrices.size() : 0);
                // 判断sessionPrices是否为空，不为空则设置
                activitySession.setActivityPrices(sessionPrices);
            }

            // 在移除之前记录当前数量
            int beforeRemove = activitySessions.size();
            // 遍历activitySessions，activitySession.activityPrices为空则移除
            activitySessions.removeIf(activitySession -> {
                boolean shouldRemove = activitySession.getActivityPrices() == null || activitySession.getActivityPrices().isEmpty();
                if (shouldRemove) {
                    log.warn("移除场次ID: {}, 原因: 价格列表为空", activitySession.getSessionid());
                }
                return shouldRemove;
            });
            int afterRemove = activitySessions.size();
            log.info("移除前场次数量: {}, 移除后场次数量: {}", beforeRemove, afterRemove);
        }


        activity.setActivitySessions(activitySessions);
        return activity;
    }

    @Override
    public void createActivity(CreateActivityDTO createActivityDTO) {
        Activity activity = new Activity();
        // 手动映射字段，因为字段名不完全匹配
        activity.setActivityName(createActivityDTO.getTitle());
        activity.setActivityContent(createActivityDTO.getContent());
        activity.setActivityDescribe(createActivityDTO.getDescription());
        activity.setActivityPlace(createActivityDTO.getLocation());
        activity.setActivityPrice(createActivityDTO.getPrice());
        activity.setActivityStartDate(createActivityDTO.getStartTime() != null ? 
            createActivityDTO.getStartTime().toString() : null);
        activity.setActivityEndDate(createActivityDTO.getEndTime() != null ? 
            createActivityDTO.getEndTime().toString() : null);
        activity.setRemaining(createActivityDTO.getMaxParticipants());
        activity.setBigid(createActivityDTO.getActivityBigTypeId());
        activity.setActivityAvatar(createActivityDTO.getImage());
        activity.setActivityState(createActivityDTO.getStatus());
        
        // 新增字段
        activity.setActivityTime1(createActivityDTO.getActivityTime1());
        activity.setActivityTime2(createActivityDTO.getActivityTime2());
        activity.setActivityType(createActivityDTO.getActivityType());
        activity.setActivityTeam(createActivityDTO.getActivityTeam());
        activity.setActivityAttention(createActivityDTO.getActivityAttention());
        activity.setActivityAddress(createActivityDTO.getActivityAddress());
        activity.setActivityLittleType(createActivityDTO.getActivityLittleType());
        activity.setActivityPerformTime(createActivityDTO.getActivityPerformTime());
        
        // 系统字段
        activity.setCreatedAt(LocalDateTime.now().toString());
        activity.setExpired(0); // 默认未过期
        activity.setActivityCommentCount(0); // 默认评论数为0
        activity.setActivityClick(0); // 默认点击量为0
        activity.setActivityBuyState("1"); // 默认售卖中
        
        activityMapper.insert(activity);
    }

    @Override
    public void updateActivity(UpdateActivityDTO updateActivityDTO) {
        Activity existingActivity = activityMapper.selectById(updateActivityDTO.getActivityid());
        if (existingActivity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        Activity activity = new Activity();
        activity.setActivityid(updateActivityDTO.getActivityid());
        
        // 手动映射字段，只更新非空字段
        if (StringUtils.hasText(updateActivityDTO.getTitle())) {
            activity.setActivityName(updateActivityDTO.getTitle());
        }
        if (StringUtils.hasText(updateActivityDTO.getContent())) {
            activity.setActivityContent(updateActivityDTO.getContent());
        }
        if (StringUtils.hasText(updateActivityDTO.getDescription())) {
            activity.setActivityDescribe(updateActivityDTO.getDescription());
        }
        if (StringUtils.hasText(updateActivityDTO.getLocation())) {
            activity.setActivityPlace(updateActivityDTO.getLocation());
        }
        if (updateActivityDTO.getPrice() != null) {
            activity.setActivityPrice(updateActivityDTO.getPrice());
        }
        if (updateActivityDTO.getStartTime() != null) {
            activity.setActivityStartDate(updateActivityDTO.getStartTime().toString());
        }
        if (updateActivityDTO.getEndTime() != null) {
            activity.setActivityEndDate(updateActivityDTO.getEndTime().toString());
        }
        if (updateActivityDTO.getMaxParticipants() != null) {
            activity.setRemaining(updateActivityDTO.getMaxParticipants());
        }
        if (updateActivityDTO.getActivityBigTypeId() != null) {
            activity.setBigid(updateActivityDTO.getActivityBigTypeId());
        }
        if (StringUtils.hasText(updateActivityDTO.getImage())) {
            activity.setActivityAvatar(updateActivityDTO.getImage());
        }
        if (updateActivityDTO.getStatus() != null) {
            activity.setActivityState(updateActivityDTO.getStatus());
        }
        
        // 新增字段
        if (StringUtils.hasText(updateActivityDTO.getActivityTime1())) {
            activity.setActivityTime1(updateActivityDTO.getActivityTime1());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityTime2())) {
            activity.setActivityTime2(updateActivityDTO.getActivityTime2());
        }
        if (updateActivityDTO.getActivityType() != null) {
            activity.setActivityType(updateActivityDTO.getActivityType());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityTeam())) {
            activity.setActivityTeam(updateActivityDTO.getActivityTeam());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityAttention())) {
            activity.setActivityAttention(updateActivityDTO.getActivityAttention());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityAddress())) {
            activity.setActivityAddress(updateActivityDTO.getActivityAddress());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityLittleType())) {
            activity.setActivityLittleType(updateActivityDTO.getActivityLittleType());
        }
        if (StringUtils.hasText(updateActivityDTO.getActivityPerformTime())) {
            activity.setActivityPerformTime(updateActivityDTO.getActivityPerformTime());
        }
        if (updateActivityDTO.getExpired() != null) {
            activity.setExpired(updateActivityDTO.getExpired());
        }
        
        activityMapper.updateById(activity);
    }

    @Override
    public void deleteActivity(Integer activityid) {
        Activity activity = activityMapper.selectById(activityid);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        activityMapper.deleteById(activityid);
    }

    @Override
    public List<Map<String, Object>> getActivityJoin(Integer activityid) {
        // TODO: 实现活动报名信息查询
        // 这里需要根据实际的报名表结构来实现
        return new ArrayList<>();
    }

    @Override
    public List<Activity> getAllActivity() {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("activityState", 1);
        queryWrapper.orderByDesc("createdAt");
        
        return activityMapper.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> getLittletypeAndBigtype() {
        // TODO: 实现获取活动分类信息
        // 这里需要查询活动大类和小类的数据
        Map<String, Object> result = new HashMap<>();
        result.put("bigTypes", new ArrayList<>());
        result.put("littleTypes", new ArrayList<>());
        
        return result;
    }

    @Override
    public void deleteSessionPrice(Integer priceId) {
        // TODO: 实现删除价格信息
        // 这里需要根据实际的价格表结构来实现
        log.info("删除价格信息: {}", priceId);
    }
} 